package com.example.myapplication.Permission;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class PermissionUtils {

    private static final int PERMISSION_REQUEST_CODE = 101;

    @RequiresApi(api = Build.VERSION_CODES.S)
    public static boolean checkPermissions(AppCompatActivity activity) {
        String[] permissions = new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH_ADVERTISE,
                Manifest.permission.BLUETOOTH_CONNECT

        };
        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            int result = ContextCompat.checkSelfPermission(activity, permission);
            if (result != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        return allPermissionsGranted;
    }

    @RequiresApi(api = Build.VERSION_CODES.S)
    public static void requestPermissions(AppCompatActivity activity) {
        String[] permissions = new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH_ADVERTISE,
                Manifest.permission.BLUETOOTH_CONNECT

        };

        ActivityCompat.requestPermissions(activity, permissions, PERMISSION_REQUEST_CODE);
    }

    public static void onRequestPermissionsResult(AppCompatActivity activity, int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;

            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    Toast.makeText(activity, "未授予权限：" + permissions[i], Toast.LENGTH_SHORT).show();
                }
            }
            if (!allPermissionsGranted) {
                // 权限被拒绝，无法执行相关操作
                Toast.makeText(activity, "请打开权限！", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
